import axios from 'axios'
import { Toast } from 'antd-mobile'
import { getTokenInfo, setTokenInfo } from './storege'
import { Logout, saveToken } from '@/store/action/login'
import history from './history'
import store from '@/store'
const baseURL = 'http://toutiao.itheima.net/v1_0'
const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 2. 设置请求拦截器和响应拦截器
instance.interceptors.request.use((config) => {
  const token = getTokenInfo().token
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})
//3. 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (!error.response) {
      Toast.info('服务器繁忙')
      return Promise.reject(error)
    }
    const { config } = error
    if (error.response === 401) {
      Toast.info(error.response.data.message, 1)
      return Promise.reject(error)
    }

    const { refresh_token } = getTokenInfo()
    if (!refresh_token) {
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(error)
    }

    try {
      const res = await axios({
        method: 'put',
        url: baseURL + 'authorizations',
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      })
      // 刷新成功
      // 把新的token保存起来
      const tokenInfo = {
        token: res.data.data.token,
        refresh_token: refresh_token,
      }
      // console.log(tokenInfo)
      // 保存到redux中
      store.dispatch(saveToken(tokenInfo))
      // 保存到localstorage中
      setTokenInfo(tokenInfo)

      // token刷新成功后，重新把最开始失败的请求重新发一次
      return instance(config)
    } catch {
      // 刷新token失败, 刷新token过期
      store.dispatch(Logout())
      // 跳转到登录页
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      Toast.info('登录信息失效，请重新登录')
      return Promise.reject(error)
    }
  }
)
export default instance
